import traceback

import pymysql
from pymysql.cursors import DictCursor


class MysqlUtil:
    def __init__(self):
        self.connection = None
        self.db = 'student_system'
        self.host = 'localhost'
        self.password = 'root'
        self.user = 'root'
        self.charset = 'utf8'
        self.connect()

    def connect(self):
        try:
            self.connection = pymysql.connect(
                db='student_system',
                host='localhost',
                password='root',
                user='root',
                charset='utf8',
                cursorclass=DictCursor
            )
            print(f"数据库连接成功")
            # print(f"数据库连接成功：{dir(self.connection)}")
        except Exception as ex:
            print(f"连接失败: {ex}")

    def execute(self, sql_query):
        """
        执行sql语句 ,增删改
        :param sql_query:语句
        :return:影响的条数
        """
        try:
            with self.connection.cursor() as cursors:
                result = cursors.execute(sql_query)
            self.connection.commit()
            return result
        except Exception as ex:
            self.traceback(ex)
            self.connection.rollback()
            return 0

    def find(self, sql_query, fetch_one=False):
        """
        查找一条记录或者多条记录
        :param sql_query:sql语句
        :param fetch_one:是否是查询一条 Ture：一条
        :return: 返回影响条数
        """
        try:
            with self.connection.cursor() as cursors:
                cursors.execute(sql_query)
                if fetch_one:
                    result = cursors.fetchone()
                else:
                    result = cursors.fetchall()
            return result
        except Exception as ex:
            self.traceback(ex)
            return 0

    @staticmethod
    def traceback(ex):
        with open("log.txt", "a") as file:
            traceback.print_exc(file=file)
            file.write(f"异常信息: {str(ex)}\n")
            file.flush()
    def close(self):
        if getattr(self,"connection",0):
            self.connection.close()
    def __del__(self):
        self.close()

if __name__ == '__main__':
    mysql = MysqlUtil()
    if mysql.connection:
        try:
            sql='select version()'
            print(f"数据库版本: {mysql.find(sql, True)}")
        except Exception as e:
            print(f"执行查询失败: {e}")
    else:
        print(f"数据库连接失败")
